package cn.mrcode.wxsdk.web;

import cn.mrcode.wxsdk.core.CoreInit;
import cn.mrcode.wxsdk.core.Init;
import cn.mrcode.wxsdk.core.context.ConfigContext;
import cn.mrcode.wxsdk.core.dialogue.common.PublicAccount;
import cn.mrcode.wxsdk.core.dialogue.common.util.ClassUtil;
import cn.mrcode.wxsdk.core.dialogue.service.CommonService;
import cn.mrcode.wxsdk.web.common.ticket.lifeCycle.ITicketService;
import cn.mrcode.wxsdk.web.common.ticket.lifeCycle.distributed.TicketDistributedService;
import cn.mrcode.wxsdk.web.common.ticket.lifeCycle.single.TicketSingleService;
import cn.mrcode.wxsdk.web.service.JsSdkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * web模块：初始化
 * @author zhuqiang
 * @version V1.0
 * @date 2016/6/15 16:59
 */
public class WebInit implements Init {
    private static Logger log = LoggerFactory.getLogger(WebInit.class);
    private ConfigContext configContext;

    public WebInit() {
        this(null,null);
    }

    /**
     * @param configName 配置文件名称，可为null；默认为sdk中的配置文件
     * @param id 每个应用的唯一id，用来分辨是谁在使用本sdk;可为null，默认为本机ip
     */
    public WebInit(String configName,String id) {
        CoreInit coreInit = new CoreInit(configName,id);
/*        if(coreInit.isInitReady()){
            init(coreInit.getConfigContext());
        }*/
        this.configContext = coreInit.getConfigContext();
        init(configContext);
    }

    @Override
    public void init(ConfigContext configContext) {
        // 初始化iTicketService 做尝试操作，保证基础的token能使用
        try {
            log.info("休眠开始：使用休眠策略5秒，保证本地token有足够的时间被刷新");
            TimeUnit.SECONDS.sleep(5);
            log.info("休眠结束：使用休眠策略5秒，保证本地token有足够的时间被刷新");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        HashMap<String, PublicAccount> publicAccountMap = configContext.getDirstributedConfig().getPublicAccountMap();
        int count = 1;
        log.info("*******  尝试获取appId可用token，以检测部分sdk配置文件是否一致，如果经过n次尝试任然获取不到。请检查所有机器中的sdk配置文件是否一致 *******");
        for (Map.Entry<String, PublicAccount> ent : publicAccountMap.entrySet()) {
            PublicAccount pa = ent.getValue();
            log.info("进度：" + count + "/" + publicAccountMap.size() + "尝试获取appId=" + ent.getKey() + " 的token，");
            String accesstoken = null;
            for (; ; ) {
                if (accesstoken == null) {
                    accesstoken = CommonService.getAccesstoken(pa.getAppID(), pa.getAppSecret());
                } else {
                    break;
                }
            }
            count++;
        }
        ClassUtil.setStaticField(JsSdkService.class, "iTicketService", this.initITicketService(configContext));
    }

    /**
     * 用于初始化 TicketService
     */
    public ITicketService initITicketService(ConfigContext configContext) {
        ITicketService iTicketService;
        if (!configContext.isDistributedMode()) {
            iTicketService = TicketSingleService.getInstance();
        } else {
            ConfigContext.DistributedConfig dirstributedConfig = configContext.getDirstributedConfig();
            int sessionTimeout = dirstributedConfig.getSessionTimeout();
            String zkServiceList = dirstributedConfig.getZkServiceList();
            HashMap<String, PublicAccount> publicAccountMap = dirstributedConfig.getPublicAccountMap();
//            iTicketService = TicketDistributedService.getInstance(sessionTimeout, zkServiceList, jssdkTicketRootPath, publicAccountMap);
            iTicketService = TicketDistributedService.getInstance(sessionTimeout, zkServiceList, publicAccountMap);
        }
        return iTicketService;
    }

    @Override
    public ConfigContext getConfigContext() {
        return this.configContext;
    }

}
